Experimental optional compression support for page cache
[lhc/web/wiklou.git] / includes / Article.php
1 <?
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
4
5 class Article {
6 /* private */ var $mContent, $mContentLoaded;
7 /* private */ var $mUser, $mTimestamp, $mUserText;
8 /* private */ var $mCounter, $mComment, $mCountAdjustment;
9 /* private */ var $mMinorEdit, $mRedirectedFrom;
10 /* private */ var $mTouched, $mFileCache;
11
12 function Article() { $this->clear(); }
13
14 /* private */ function clear()
15 {
16 $this->mContentLoaded = false;
17 $this->mUser = $this->mCounter = -1; # Not loaded
18 $this->mRedirectedFrom = $this->mUserText =
19 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
20 $this->mCountAdjustment = 0;
21 $this->mTouched = "19700101000000";
22 }
23
24 /* static */ function newFromID( $newid )
25 {
26 global $wgOut, $wgTitle, $wgArticle;
27 $a = new Article();
28 $n = Article::nameOf( $newid );
29
30 $wgTitle = Title::newFromDBkey( $n );
31 $wgTitle->resetArticleID( $newid );
32
33 return $a;
34 }
35
36 /* static */ function nameOf( $id )
37 {
38 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
39 "cur_id={$id}";
40 $res = wfQuery( $sql, "Article::nameOf" );
41 if ( 0 == wfNumRows( $res ) ) { return NULL; }
42
43 $s = wfFetchObject( $res );
44 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
45 return $n;
46 }
47
48 # Note that getContent/loadContent may follow redirects if
49 # not told otherwise, and so may cause a change to wgTitle.
50
51 function getContent( $noredir = false )
52 {
53 global $action,$wgTitle; # From query string
54 wfProfileIn( "Article::getContent" );
55
56 if ( 0 == $this->getID() ) {
57 if ( "edit" == $action ) {
58
59 global $wgTitle;
60 return ""; # was "newarticletext", now moved above the box)
61
62
63 }
64 wfProfileOut();
65 return wfMsg( "noarticletext" );
66 } else {
67 $this->loadContent( $noredir );
68 wfProfileOut();
69
70 if(
71 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
72 ( $wgTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
73 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$wgTitle->getText()) &&
74 $action=="view"
75 )
76 {
77 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
78 else {
79 return $this->mContent;
80 }
81 }
82 }
83
84 function loadContent( $noredir = false )
85 {
86 global $wgOut, $wgTitle;
87 global $oldid, $redirect; # From query
88
89 if ( $this->mContentLoaded ) return;
90 $fname = "Article::loadContent";
91
92 # Pre-fill content with error message so that if something
93 # fails we'll have something telling us what we intended.
94
95 $t = $wgTitle->getPrefixedText();
96 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
97 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
98 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
99
100 if ( ! $oldid ) { # Retrieve current version
101 $id = $this->getID();
102 if ( 0 == $id ) return;
103
104 $sql = "SELECT " .
105 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
106 "FROM cur WHERE cur_id={$id}";
107 $res = wfQuery( $sql, $fname );
108 if ( 0 == wfNumRows( $res ) ) { return; }
109
110 $s = wfFetchObject( $res );
111
112 # If we got a redirect, follow it (unless we've been told
113 # not to by either the function parameter or the query
114
115 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
116 ( preg_match( "/^#redirect/i", $s->cur_text ) ) ) {
117 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
118 $s->cur_text, $m ) ) {
119 $rt = Title::newFromText( $m[1] );
120
121 # Gotta hand redirects to special pages differently:
122 # Fill the HTTP response "Location" header and ignore
123 # the rest of the page we're on.
124
125 if ( $rt->getInterwiki() != "" ) {
126 $wgOut->redirect( $rt->getFullURL() ) ;
127 return;
128 }
129 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
130 $wgOut->redirect( wfLocalUrl(
131 $rt->getPrefixedURL() ) );
132 return;
133 }
134 $rid = $rt->getArticleID();
135 if ( 0 != $rid ) {
136 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
137 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
138 $res = wfQuery( $sql, $fname );
139
140 if ( 0 != wfNumRows( $res ) ) {
141 $this->mRedirectedFrom = $wgTitle->getPrefixedText();
142 $wgTitle = $rt;
143 $s = wfFetchObject( $res );
144 }
145 }
146 }
147 }
148 $this->mContent = $s->cur_text;
149 $this->mUser = $s->cur_user;
150 $this->mCounter = $s->cur_counter;
151 $this->mTimestamp = $s->cur_timestamp;
152 $this->mTouched = $s->cur_touched;
153 $wgTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
154 $wgTitle->mRestrictionsLoaded = true;
155 wfFreeResult( $res );
156 } else { # oldid set, retrieve historical version
157 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
158 "WHERE old_id={$oldid}";
159 $res = wfQuery( $sql, $fname );
160 if ( 0 == wfNumRows( $res ) ) { return; }
161
162 $s = wfFetchObject( $res );
163 $this->mContent = $s->old_text;
164 $this->mUser = $s->old_user;
165 $this->mCounter = 0;
166 $this->mTimestamp = $s->old_timestamp;
167 wfFreeResult( $res );
168 }
169 $this->mContentLoaded = true;
170 }
171
172 function getID() { global $wgTitle; return $wgTitle->getArticleID(); }
173
174 function getCount()
175 {
176 if ( -1 == $this->mCounter ) {
177 $id = $this->getID();
178 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
179 }
180 return $this->mCounter;
181 }
182
183 # Would the given text make this article a "good" article (i.e.,
184 # suitable for including in the article count)?
185
186 function isCountable( $text )
187 {
188 global $wgTitle, $wgUseCommaCount;
189
190 if ( 0 != $wgTitle->getNamespace() ) { return 0; }
191 if ( preg_match( "/^#redirect/i", $text ) ) { return 0; }
192 $token = ($wgUseCommaCount ? "," : "[[" );
193 if ( false === strstr( $text, $token ) ) { return 0; }
194 return 1;
195 }
196
197 # Load the field related to the last edit time of the article.
198 # This isn't necessary for all uses, so it's only done if needed.
199
200 /* private */ function loadLastEdit()
201 {
202 global $wgOut;
203 if ( -1 != $this->mUser ) return;
204
205 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
206 "cur_comment,cur_minor_edit FROM cur WHERE " .
207 "cur_id=" . $this->getID();
208 $res = wfQuery( $sql, "Article::loadLastEdit" );
209
210 if ( wfNumRows( $res ) > 0 ) {
211 $s = wfFetchObject( $res );
212 $this->mUser = $s->cur_user;
213 $this->mUserText = $s->cur_user_text;
214 $this->mTimestamp = $s->cur_timestamp;
215 $this->mComment = $s->cur_comment;
216 $this->mMinorEdit = $s->cur_minor_edit;
217 }
218 }
219
220 function getTimestamp()
221 {
222 $this->loadLastEdit();
223 return $this->mTimestamp;
224 }
225
226 function getUser()
227 {
228 $this->loadLastEdit();
229 return $this->mUser;
230 }
231
232 function getUserText()
233 {
234 $this->loadLastEdit();
235 return $this->mUserText;
236 }
237
238 function getComment()
239 {
240 $this->loadLastEdit();
241 return $this->mComment;
242 }
243
244 function getMinorEdit()
245 {
246 $this->loadLastEdit();
247 return $this->mMinorEdit;
248 }
249
250 # This is the default action of the script: just view the page of
251 # the given title.
252
253 function view()
254 {
255 global $wgUser, $wgOut, $wgTitle, $wgLang;
256 global $oldid, $diff; # From query
257 global $wgLinkCache;
258 wfProfileIn( "Article::view" );
259
260 $wgOut->setArticleFlag( true );
261 $wgOut->setRobotpolicy( "index,follow" );
262
263 # If we got diff and oldid in the query, we want to see a
264 # diff page instead of the article.
265
266 if ( isset( $diff ) ) {
267 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
268 $de = new DifferenceEngine( $oldid, $diff );
269 $de->showDiffPage();
270 wfProfileOut();
271 return;
272 }
273 $text = $this->getContent(); # May change wgTitle!
274 $wgOut->setPageTitle( $wgTitle->getPrefixedText() );
275 $wgOut->setHTMLTitle( $wgTitle->getPrefixedText() .
276 " - " . wfMsg( "wikititlesuffix" ) );
277
278 # We're looking at an old revision
279
280 if ( $oldid ) {
281 $this->setOldSubtitle();
282 $wgOut->setRobotpolicy( "noindex,follow" );
283 }
284 if ( "" != $this->mRedirectedFrom ) {
285 $sk = $wgUser->getSkin();
286 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
287 "redirect=no" );
288 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
289 $wgOut->setSubtitle( $s );
290 }
291 $wgOut->checkLastModified( $this->mTouched );
292 $this->tryFileCache();
293 $wgLinkCache->preFill( $wgTitle );
294 $wgOut->addWikiText( $text );
295
296 # If the article we've just shown is in the "Image" namespace,
297 # follow it with the history list and link list for the image
298 # it describes.
299
300 if ( Namespace::getImage() == $wgTitle->getNamespace() ) {
301 $this->imageHistory();
302 $this->imageLinks();
303 }
304 $this->viewUpdates();
305 wfProfileOut();
306 }
307
308 # This is the function that gets called for "action=edit".
309
310 function edit()
311 {
312 global $wgOut, $wgUser, $wgTitle;
313 global $wpTextbox1, $wpSummary, $wpSave, $wpPreview;
314 global $wpMinoredit, $wpEdittime, $wpTextbox2;
315
316 $fields = array( "wpTextbox1", "wpSummary", "wpTextbox2" );
317 wfCleanFormFields( $fields );
318
319 if ( ! $wgTitle->userCanEdit() ) {
320 $this->view();
321 return;
322 }
323 if ( $wgUser->isBlocked() ) {
324 $this->blockedIPpage();
325 return;
326 }
327 if ( wfReadOnly() ) {
328 if( isset( $wpSave ) or isset( $wpPreview ) ) {
329 $this->editForm( "preview" );
330 } else {
331 $wgOut->readOnlyPage();
332 }
333 return;
334 }
335 if ( $_SERVER['REQUEST_METHOD'] != "POST" ) unset( $wpSave );
336 if ( isset( $wpSave ) ) {
337 $this->editForm( "save" );
338 } else if ( isset( $wpPreview ) ) {
339 $this->editForm( "preview" );
340 } else { # First time through
341 $this->editForm( "initial" );
342 }
343 }
344
345 # Since there is only one text field on the edit form,
346 # pressing <enter> will cause the form to be submitted, but
347 # the submit button value won't appear in the query, so we
348 # Fake it here before going back to edit(). This is kind of
349 # ugly, but it helps some old URLs to still work.
350
351 function submit()
352 {
353 global $wpSave, $wpPreview;
354 if ( ! isset( $wpPreview ) ) { $wpSave = 1; }
355
356 $this->edit();
357 }
358
359 # The edit form is self-submitting, so that when things like
360 # preview and edit conflicts occur, we get the same form back
361 # with the extra stuff added. Only when the final submission
362 # is made and all is well do we actually save and redirect to
363 # the newly-edited page.
364
365 function editForm( $formtype )
366 {
367 global $wgOut, $wgUser, $wgTitle;
368 global $wpTextbox1, $wpSummary, $wpWatchthis;
369 global $wpSave, $wpPreview;
370 global $wpMinoredit, $wpEdittime, $wpTextbox2;
371 global $oldid, $redirect;
372 global $wgLang;
373
374 $sk = $wgUser->getSkin();
375 $isConflict = false;
376 $wpTextbox1 = rtrim ( $wpTextbox1 ) ; # To avoid text getting longer on each preview
377
378 if(!$wgTitle->getArticleID()) { # new article
379
380 $wgOut->addWikiText(wfmsg("newarticletext"));
381
382 }
383
384 # Attempt submission here. This will check for edit conflicts,
385 # and redundantly check for locked database, blocked IPs, etc.
386 # that edit() already checked just in case someone tries to sneak
387 # in the back door with a hand-edited submission URL.
388
389 if ( "save" == $formtype ) {
390 if ( $wgUser->isBlocked() ) {
391 $this->blockedIPpage();
392 return;
393 }
394 if ( wfReadOnly() ) {
395 $wgOut->readOnlyPage();
396 return;
397 }
398 # If article is new, insert it.
399
400 $aid = $wgTitle->getArticleID();
401 if ( 0 == $aid ) {
402 # we need to strip Windoze linebreaks because some browsers
403 # append them and the string comparison fails
404 if ( ( "" == $wpTextbox1 ) ||
405 ( wfMsg( "newarticletext" ) == rtrim( preg_replace("/\r/","",$wpTextbox1) ) ) ) {
406 $wgOut->redirect( wfLocalUrl(
407 $wgTitle->getPrefixedURL() ) );
408 return;
409 }
410 $this->mCountAdjustment = $this->isCountable( $wpTextbox1 );
411 $this->insertNewArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
412 return;
413 }
414 # Article exists. Check for edit conflict.
415
416 $this->clear(); # Force reload of dates, etc.
417 if ( $this->getTimestamp() != $wpEdittime ) { $isConflict = true; }
418 $u = $wgUser->getID();
419
420 # Supress edit conflict with self
421
422 if ( ( 0 != $u ) && ( $this->getUser() == $u ) ) {
423 $isConflict = false;
424 }
425 if ( ! $isConflict ) {
426 # All's well: update the article here
427 $this->updateArticle( $wpTextbox1, $wpSummary, $wpMinoredit, $wpWatchthis );
428 return;
429 }
430 }
431 # First time through: get contents, set time for conflict
432 # checking, etc.
433
434 if ( "initial" == $formtype ) {
435 $wpEdittime = $this->getTimestamp();
436 $wpTextbox1 = $this->getContent();
437 $wpSummary = "";
438 }
439 $wgOut->setRobotpolicy( "noindex,nofollow" );
440 $wgOut->setArticleFlag( false );
441
442 if ( $isConflict ) {
443 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
444 wfMsg( "editconflict" ) );
445 $wgOut->setPageTitle( $s );
446 $wgOut->addHTML( wfMsg( "explainconflict" ) );
447
448 $wpTextbox2 = $wpTextbox1;
449 $wpTextbox1 = $this->getContent();
450 $wpEdittime = $this->getTimestamp();
451 } else {
452 $s = str_replace( "$1", $wgTitle->getPrefixedText(),
453 wfMsg( "editing" ) );
454 $wgOut->setPageTitle( $s );
455 if ( $oldid ) {
456 $this->setOldSubtitle();
457 $wgOut->addHTML( wfMsg( "editingold" ) );
458 }
459 }
460
461 if( wfReadOnly() ) {
462 $wgOut->addHTML( "<strong>" .
463 wfMsg( "readonlywarning" ) .
464 "</strong>" );
465 }
466 if( $wgTitle->isProtected() ) {
467 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
468 "</strong><br />\n" );
469 }
470
471 $kblength = (int)(strlen( $wpTextbox1 ) / 1024);
472 if( $kblength > 29 ) {
473 $wgOut->addHTML( "<strong>" .
474 str_replace( '$1', $kblength , wfMsg( "longpagewarning" ) )
475 . "</strong>" );
476 }
477
478 $rows = $wgUser->getOption( "rows" );
479 $cols = $wgUser->getOption( "cols" );
480
481 $ew = $wgUser->getOption( "editwidth" );
482 if ( $ew ) $ew = " style=\"width:100%\"";
483 else $ew = "" ;
484
485 $q = "action=submit";
486 if ( "no" == $redirect ) { $q .= "&redirect=no"; }
487 $action = wfEscapeHTML( wfLocalUrl( $wgTitle->getPrefixedURL(), $q ) );
488
489 $summary = wfMsg( "summary" );
490 $minor = wfMsg( "minoredit" );
491 $watchthis = wfMsg ("watchthis");
492 $save = wfMsg( "savearticle" );
493 $prev = wfMsg( "showpreview" );
494
495 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedURL(),
496 wfMsg( "cancel" ) );
497 $edithelp = $sk->makeKnownLink( wfMsg( "edithelppage" ),
498 wfMsg( "edithelp" ) );
499 $copywarn = str_replace( "$1", $sk->makeKnownLink(
500 wfMsg( "copyrightpage" ) ), wfMsg( "copyrightwarning" ) );
501
502 $wpTextbox1 = wfEscapeHTML( $wpTextbox1 );
503 $wpTextbox2 = wfEscapeHTML( $wpTextbox2 );
504 $wpSummary = wfEscapeHTML( $wpSummary );
505
506 // activate checkboxes if user wants them to be always active
507 if (!$wpPreview && $wgUser->getOption("watchdefault")) $wpWatchthis=1;
508 if (!$wpPreview && $wgUser->getOption("minordefault")) $wpMinoredit=1;
509
510 // activate checkbox also if user is already watching the page,
511 // require wpWatchthis to be unset so that second condition is not
512 // checked unnecessarily
513 if (!$wpWatchthis && !$wpPreview && $wgTitle->userIsWatching()) $wpWatchthis=1;
514
515 if ( 0 != $wgUser->getID() ) {
516 $checkboxhtml=
517 "<input tabindex=3 type=checkbox value=1 name='wpMinoredit'".($wpMinoredit?" checked":"").">{$minor}".
518 "<input tabindex=4 type=checkbox name='wpWatchthis'".($wpWatchthis?" checked":"").">{$watchthis}<br>";
519
520 } else {
521 $checkboxhtml="";
522 }
523
524
525 if ( "preview" == $formtype) {
526
527 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
528 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large><P>\n";
529 if ( $isConflict ) {
530 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
531 "</h2>\n";
532 }
533 $previewtext = wfUnescapeHTML( $wpTextbox1 );
534
535 if($wgUser->getOption("previewontop")) {
536 $wgOut->addHTML($previewhead);
537 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) ."\n\n");
538 }
539 }
540 $wgOut->addHTML( "
541 <form id=\"editform\" method=\"post\" action=\"$action\"
542 enctype=\"application/x-www-form-urlencoded\">
543 <br clear=\"all\" />
544 <textarea tabindex=1 name=\"wpTextbox1\" rows={$rows}
545 cols={$cols}{$ew} wrap=\"virtual\">" .
546 $wgLang->recodeForEdit( $wpTextbox1 ) .
547 "
548 </textarea><br>
549 {$summary}: <input tabindex=2 type=text value=\"{$wpSummary}\"
550 name=\"wpSummary\" maxlength=200 size=60><br>
551 {$checkboxhtml}
552 <input tabindex=5 type=submit value=\"{$save}\" name=\"wpSave\">
553 <input tabindex=6 type=submit value=\"{$prev}\" name=\"wpPreview\">
554 <em>{$cancel}</em> | <em>{$edithelp}</em>
555 <br><br>{$copywarn}
556 <input type=hidden value=\"{$wpEdittime}\" name=\"wpEdittime\">\n" );
557
558 if ( $isConflict ) {
559 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
560 DifferenceEngine::showDiff( $wpTextbox2, $wpTextbox1,
561 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
562
563 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
564 <textarea tabindex=6 name=\"wpTextbox2\" rows={$rows} cols={$cols} wrap=virtual>"
565 . $wgLang->recodeForEdit( $wpTextbox2 ) .
566 "
567 </textarea>" );
568 }
569 $wgOut->addHTML( "</form>\n" );
570 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
571 $wgOut->addHTML($previewhead);
572 $wgOut->addWikiText( $this->preSaveTransform( $previewtext ) );
573 }
574
575 }
576
577 # Theoretically we could defer these whole insert and update
578 # functions for after display, but that's taking a big leap
579 # of faith, and we want to be able to report database
580 # errors at some point.
581
582 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
583 {
584 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
585 $fname = "Article::insertNewArticle";
586
587 $ns = $wgTitle->getNamespace();
588 $ttl = $wgTitle->getDBkey();
589 $text = $this->preSaveTransform( $text );
590 if ( preg_match( "/^#redirect/i", $text ) ) { $redir = 1; }
591 else { $redir = 0; }
592
593 $now = wfTimestampNow();
594 $won = wfInvertTimestamp( $now );
595 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
596 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
597 "cur_restrictions,cur_user_text,cur_is_redirect," .
598 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
599 wfStrencode( $text ) . "', '" .
600 wfStrencode( $summary ) . "', '" .
601 $wgUser->getID() . "', '{$now}', " .
602 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
603 wfStrencode( $wgUser->getName() ) . "', $redir, 1, RAND(), '{$now}', '{$won}')";
604 $res = wfQuery( $sql, $fname );
605
606 $newid = wfInsertId();
607 $wgTitle->resetArticleID( $newid );
608
609 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
610 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
611 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
612 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
613 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
614 wfStrencode( $wgUser->getName() ) . "','" .
615 wfStrencode( $summary ) . "',0,0," .
616 ( $wgUser->isBot() ? 1 : 0 ) . ")";
617 wfQuery( $sql, $fname );
618 if ($watchthis) {
619 if(!$wgTitle->userIsWatching()) $this->watch();
620 } else {
621 if ( $wgTitle->userIsWatching() ) {
622 $this->unwatch();
623 }
624 }
625
626 $this->showArticle( $text, wfMsg( "newarticle" ) );
627 }
628
629 function updateArticle( $text, $summary, $minor, $watchthis )
630 {
631 global $wgOut, $wgUser, $wgTitle, $wgLinkCache;
632 global $wgDBtransactions;
633 $fname = "Article::updateArticle";
634
635 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
636 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
637 if ( preg_match( "/^(#redirect[^\\n]+)/i", $text, $m ) ) {
638 $redir = 1;
639 $text = $m[1] . "\n"; # Remove all content but redirect
640 }
641 else { $redir = 0; }
642 $this->loadLastEdit();
643
644 $text = $this->preSaveTransform( $text );
645
646 # Update article, but only if changed.
647
648 if( $wgDBtransactions ) {
649 $sql = "BEGIN";
650 wfQuery( $sql );
651 }
652 $oldtext = $this->getContent( true );
653
654 if ( 0 != strcmp( $text, $oldtext ) ) {
655 $this->mCountAdjustment = $this->isCountable( $text )
656 - $this->isCountable( $oldtext );
657
658 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
659 "old_comment,old_user,old_user_text,old_timestamp," .
660 "old_minor_edit,inverse_timestamp) VALUES (" .
661 $wgTitle->getNamespace() . ", '" .
662 wfStrencode( $wgTitle->getDBkey() ) . "', '" .
663 wfStrencode( $oldtext ) . "', '" .
664 wfStrencode( $this->getComment() ) . "', " .
665 $this->getUser() . ", '" .
666 wfStrencode( $this->getUserText() ) . "', '" .
667 $this->getTimestamp() . "', " . $me1 . ", '" .
668 wfInvertTimestamp( $this->getTimestamp() ) . "')";
669 $res = wfQuery( $sql, $fname );
670 $oldid = wfInsertID( $res );
671
672 $now = wfTimestampNow();
673 $won = wfInvertTimestamp( $now );
674 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
675 "',cur_comment='" . wfStrencode( $summary ) .
676 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
677 ",cur_timestamp='{$now}',cur_user_text='" .
678 wfStrencode( $wgUser->getName() ) .
679 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
680 "WHERE cur_id=" . $this->getID();
681 wfQuery( $sql, $fname );
682
683 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
684 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
685 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
686 "'{$now}','{$now}'," . $wgTitle->getNamespace() . ",'" .
687 wfStrencode( $wgTitle->getDBkey() ) . "',0,{$me2}," .
688 ( $wgUser->isBot() ? 1 : 0 ) . "," .
689 $this->getID() . "," . $wgUser->getID() . ",'" .
690 wfStrencode( $wgUser->getName() ) . "','" .
691 wfStrencode( $summary ) . "',0,{$oldid})";
692 wfQuery( $sql, $fname );
693
694 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
695 "WHERE rc_namespace=" . $wgTitle->getNamespace() . " AND " .
696 "rc_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' AND " .
697 "rc_timestamp='" . $this->getTimestamp() . "'";
698 wfQuery( $sql, $fname );
699
700 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
701 "WHERE rc_cur_id=" . $this->getID();
702 wfQuery( $sql, $fname );
703 }
704 if( $wgDBtransactions ) {
705 $sql = "COMMIT";
706 wfQuery( $sql );
707 }
708
709 if ($watchthis) {
710 if (!$wgTitle->userIsWatching()) $this->watch();
711 } else {
712 if ( $wgTitle->userIsWatching() ) {
713 $this->unwatch();
714 }
715 }
716
717 $this->showArticle( $text, wfMsg( "updated" ) );
718 }
719
720 # After we've either updated or inserted the article, update
721 # the link tables and redirect to the new page.
722
723 function showArticle( $text, $subtitle )
724 {
725 global $wgOut, $wgTitle, $wgUser, $wgLinkCache;
726
727 $wgLinkCache = new LinkCache();
728 $wgOut->addWikiText( $text ); # Just to update links
729
730 $this->editUpdates( $text );
731 if( preg_match( "/^#redirect/i", $text ) )
732 $r = "redirect=no";
733 else
734 $r = "";
735 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL(), $r ) );
736 }
737
738 # If the page we've just displayed is in the "Image" namespace,
739 # we follow it with an upload history of the image and its usage.
740
741 function imageHistory()
742 {
743 global $wgUser, $wgOut, $wgLang, $wgTitle;
744 $fname = "Article::imageHistory";
745
746 $sql = "SELECT img_size,img_description,img_user," .
747 "img_user_text,img_timestamp FROM image WHERE " .
748 "img_name='" . wfStrencode( $wgTitle->getDBkey() ) . "'";
749 $res = wfQuery( $sql, $fname );
750
751 if ( 0 == wfNumRows( $res ) ) { return; }
752
753 $sk = $wgUser->getSkin();
754 $s = $sk->beginImageHistoryList();
755
756 $line = wfFetchObject( $res );
757 $s .= $sk->imageHistoryLine( true, $line->img_timestamp,
758 $wgTitle->getText(), $line->img_user,
759 $line->img_user_text, $line->img_size, $line->img_description );
760
761 $sql = "SELECT oi_size,oi_description,oi_user," .
762 "oi_user_text,oi_timestamp,oi_archive_name FROM oldimage WHERE " .
763 "oi_name='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
764 "ORDER BY oi_timestamp DESC";
765 $res = wfQuery( $sql, $fname );
766
767 while ( $line = wfFetchObject( $res ) ) {
768 $s .= $sk->imageHistoryLine( false, $line->oi_timestamp,
769 $line->oi_archive_name, $line->oi_user,
770 $line->oi_user_text, $line->oi_size, $line->oi_description );
771 }
772 $s .= $sk->endImageHistoryList();
773 $wgOut->addHTML( $s );
774 }
775
776 function imageLinks()
777 {
778 global $wgUser, $wgOut, $wgTitle;
779
780 $wgOut->addHTML( "<h2>" . wfMsg( "imagelinks" ) . "</h2>\n" );
781
782 $sql = "SELECT il_from FROM imagelinks WHERE il_to='" .
783 wfStrencode( $wgTitle->getDBkey() ) . "'";
784 $res = wfQuery( $sql, "Article::imageLinks" );
785
786 if ( 0 == wfNumRows( $res ) ) {
787 $wgOut->addHtml( "<p>" . wfMsg( "nolinkstoimage" ) . "\n" );
788 return;
789 }
790 $wgOut->addHTML( "<p>" . wfMsg( "linkstoimage" ) . "\n<ul>" );
791
792 $sk = $wgUser->getSkin();
793 while ( $s = wfFetchObject( $res ) ) {
794 $name = $s->il_from;
795 $link = $sk->makeKnownLink( $name, "" );
796 $wgOut->addHTML( "<li>{$link}</li>\n" );
797 }
798 $wgOut->addHTML( "</ul>\n" );
799 }
800
801 # Add this page to my watchlist
802
803 function watch()
804 {
805 global $wgUser, $wgTitle, $wgOut, $wgLang;
806 global $wgDeferredUpdateList;
807
808 if ( 0 == $wgUser->getID() ) {
809 $wgOut->errorpage( "watchnologin", "watchnologintext" );
810 return;
811 }
812 if ( wfReadOnly() ) {
813 $wgOut->readOnlyPage();
814 return;
815 }
816 $wgUser->addWatch( $wgTitle );
817
818 $wgOut->setPagetitle( wfMsg( "addedwatch" ) );
819 $wgOut->setRobotpolicy( "noindex,follow" );
820
821 $sk = $wgUser->getSkin() ;
822 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
823
824 $text = str_replace( "$1", $link ,
825 wfMsg( "addedwatchtext" ) );
826 $wgOut->addHTML( $text );
827
828 $up = new UserUpdate();
829 array_push( $wgDeferredUpdateList, $up );
830
831 $wgOut->returnToMain( false );
832 }
833
834 function unwatch()
835 {
836 global $wgUser, $wgTitle, $wgOut, $wgLang;
837 global $wgDeferredUpdateList;
838
839 if ( 0 == $wgUser->getID() ) {
840 $wgOut->errorpage( "watchnologin", "watchnologintext" );
841 return;
842 }
843 if ( wfReadOnly() ) {
844 $wgOut->readOnlyPage();
845 return;
846 }
847 $wgUser->removeWatch( $wgTitle );
848
849 $wgOut->setPagetitle( wfMsg( "removedwatch" ) );
850 $wgOut->setRobotpolicy( "noindex,follow" );
851
852 $sk = $wgUser->getSkin() ;
853 $link = $sk->makeKnownLink ( $wgTitle->getPrefixedText() ) ;
854
855 $text = str_replace( "$1", $link ,
856 wfMsg( "removedwatchtext" ) );
857 $wgOut->addHTML( $text );
858
859 $up = new UserUpdate();
860 array_push( $wgDeferredUpdateList, $up );
861
862 $wgOut->returnToMain( false );
863 }
864
865 # This shares a lot of issues (and code) with Recent Changes
866
867 function history()
868 {
869 global $wgUser, $wgOut, $wgLang, $wgTitle, $offset, $limit;
870
871 # If page hasn't changed, client can cache this
872
873 $wgOut->checkLastModified( $this->getTimestamp() );
874 wfProfileIn( "Article::history" );
875
876 $wgOut->setPageTitle( $wgTitle->getPRefixedText() );
877 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
878 $wgOut->setArticleFlag( false );
879 $wgOut->setRobotpolicy( "noindex,nofollow" );
880
881 if( $wgTitle->getArticleID() == 0 ) {
882 $wgOut->addHTML( wfMsg( "nohistory" ) );
883 wfProfileOut();
884 return;
885 }
886
887 $offset = (int)$offset;
888 $limit = (int)$limit;
889 if( $limit == 0 ) $limit = 50;
890 $namespace = $wgTitle->getNamespace();
891 $title = $wgTitle->getText();
892 $sql = "SELECT old_id,old_user," .
893 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
894 "FROM old USE INDEX (name_title_timestamp) " .
895 "WHERE old_namespace={$namespace} AND " .
896 "old_title='" . wfStrencode( $wgTitle->getDBkey() ) . "' " .
897 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
898 $res = wfQuery( $sql, "Article::history" );
899
900 $revs = wfNumRows( $res );
901 if( $wgTitle->getArticleID() == 0 ) {
902 $wgOut->addHTML( wfMsg( "nohistory" ) );
903 wfProfileOut();
904 return;
905 }
906
907 $sk = $wgUser->getSkin();
908 $numbar = wfViewPrevNext(
909 $offset, $limit,
910 $wgTitle->getPrefixedText(),
911 "action=history" );
912 $s = $numbar;
913 $s .= $sk->beginHistoryList();
914
915 if($offset == 0 )
916 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
917 $this->getUserText(), $namespace,
918 $title, 0, $this->getComment(),
919 ( $this->getMinorEdit() > 0 ) );
920
921 $revs = wfNumRows( $res );
922 while ( $line = wfFetchObject( $res ) ) {
923 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
924 $line->old_user_text, $namespace,
925 $title, $line->old_id,
926 $line->old_comment, ( $line->old_minor_edit > 0 ) );
927 }
928 $s .= $sk->endHistoryList();
929 $s .= $numbar;
930 $wgOut->addHTML( $s );
931 wfProfileOut();
932 }
933
934 function protect()
935 {
936 global $wgUser, $wgOut, $wgTitle;
937
938 if ( ! $wgUser->isSysop() ) {
939 $wgOut->sysopRequired();
940 return;
941 }
942 if ( wfReadOnly() ) {
943 $wgOut->readOnlyPage();
944 return;
945 }
946 $id = $wgTitle->getArticleID();
947 if ( 0 == $id ) {
948 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
949 return;
950 }
951 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
952 "cur_restrictions='sysop' WHERE cur_id={$id}";
953 wfQuery( $sql, "Article::protect" );
954
955 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
956 }
957
958 function unprotect()
959 {
960 global $wgUser, $wgOut, $wgTitle;
961
962 if ( ! $wgUser->isSysop() ) {
963 $wgOut->sysopRequired();
964 return;
965 }
966 if ( wfReadOnly() ) {
967 $wgOut->readOnlyPage();
968 return;
969 }
970 $id = $wgTitle->getArticleID();
971 if ( 0 == $id ) {
972 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
973 return;
974 }
975 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
976 "cur_restrictions='' WHERE cur_id={$id}";
977 wfQuery( $sql, "Article::unprotect" );
978
979 $wgOut->redirect( wfLocalUrl( $wgTitle->getPrefixedURL() ) );
980 }
981
982 function delete()
983 {
984 global $wgUser, $wgOut, $wgTitle;
985 global $wpConfirm, $wpReason, $image, $oldimage;
986
987 # Anybody can delete old revisions of images; only sysops
988 # can delete articles and current images
989
990 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
991 $wgOut->sysopRequired();
992 return;
993 }
994 if ( wfReadOnly() ) {
995 $wgOut->readOnlyPage();
996 return;
997 }
998
999 # Better double-check that it hasn't been deleted yet!
1000 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
1001 if ( $image ) {
1002 if ( "" == trim( $image ) ) {
1003 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1004 return;
1005 }
1006 $sub = str_replace( "$1", $image, wfMsg( "deletesub" ) );
1007 } else {
1008 if ( ( "" == trim( $wgTitle->getText() ) )
1009 or ( $wgTitle->getArticleId() == 0 ) ) {
1010 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1011 return;
1012 }
1013 $sub = str_replace( "$1", $wgTitle->getPrefixedText(),
1014 wfMsg( "deletesub" ) );
1015 }
1016
1017 # Likewise, deleting old images doesn't require confirmation
1018 if ( $oldimage || 1 == $wpConfirm ) {
1019 $this->doDelete();
1020 return;
1021 }
1022
1023 $wgOut->setSubtitle( $sub );
1024 $wgOut->setRobotpolicy( "noindex,nofollow" );
1025 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
1026
1027 $t = $wgTitle->getPrefixedURL();
1028 $q = "action=delete";
1029
1030 if ( $image ) {
1031 $q .= "&image={$image}";
1032 } else if ( $oldimage ) {
1033 $q .= "&oldimage={$oldimage}";
1034 } else {
1035 $q .= "&title={$t}";
1036 }
1037 $formaction = wfEscapeHTML( wfLocalUrl( "", $q ) );
1038 $confirm = wfMsg( "confirm" );
1039 $check = wfMsg( "confirmcheck" );
1040 $delcom = wfMsg( "deletecomment" );
1041
1042 $wgOut->addHTML( "
1043 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
1044 <table border=0><tr><td align=right>
1045 {$delcom}:</td><td align=left>
1046 <input type=text size=20 name=\"wpReason\" value=\"{$wpReason}\">
1047 </td></tr><tr><td>&nbsp;</td></tr>
1048 <tr><td align=right>
1049 <input type=checkbox name=\"wpConfirm\" value='1'>
1050 </td><td>{$check}</td>
1051 </tr><tr><td>&nbsp;</td><td>
1052 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
1053 </td></tr></table></form>\n" );
1054
1055 $wgOut->returnToMain( false );
1056 }
1057
1058 function doDelete()
1059 {
1060 global $wgOut, $wgTitle, $wgUser, $wgLang;
1061 global $image, $oldimage, $wpReason;
1062 $fname = "Article::doDelete";
1063
1064 if ( $image ) {
1065 $dest = wfImageDir( $image );
1066 $archive = wfImageDir( $image );
1067 if ( ! unlink( "{$dest}/{$image}" ) ) {
1068 $wgOut->fileDeleteError( "{$dest}/{$image}" );
1069 return;
1070 }
1071 $sql = "DELETE FROM image WHERE img_name='" .
1072 wfStrencode( $image ) . "'";
1073 wfQuery( $sql, $fname );
1074
1075 $sql = "SELECT oi_archive_name FROM oldimage WHERE oi_name='" .
1076 wfStrencode( $image ) . "'";
1077 $res = wfQuery( $sql, $fname );
1078
1079 while ( $s = wfFetchObject( $res ) ) {
1080 $this->doDeleteOldImage( $s->oi_archive_name );
1081 }
1082 $sql = "DELETE FROM oldimage WHERE oi_name='" .
1083 wfStrencode( $image ) . "'";
1084 wfQuery( $sql, $fname );
1085
1086 # Image itself is now gone, and database is cleaned.
1087 # Now we remove the image description page.
1088
1089 $nt = Title::newFromText( $wgLang->getNsText( Namespace::getImage() ) . ":" . $image );
1090 $this->doDeleteArticle( $nt );
1091
1092 $deleted = $image;
1093 } else if ( $oldimage ) {
1094 $this->doDeleteOldImage( $oldimage );
1095 $sql = "DELETE FROM oldimage WHERE oi_archive_name='" .
1096 wfStrencode( $oldimage ) . "'";
1097 wfQuery( $sql, $fname );
1098
1099 $deleted = $oldimage;
1100 } else {
1101 $this->doDeleteArticle( $wgTitle );
1102 $deleted = $wgTitle->getPrefixedText();
1103 }
1104 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1105 $wgOut->setRobotpolicy( "noindex,nofollow" );
1106
1107 $sk = $wgUser->getSkin();
1108 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1109 Namespace::getWikipedia() ) .
1110 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
1111
1112 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
1113 $text = str_replace( "$2", $loglink, $text );
1114
1115 $wgOut->addHTML( "<p>" . $text );
1116 $wgOut->returnToMain( false );
1117 }
1118
1119 function doDeleteOldImage( $oldimage )
1120 {
1121 global $wgOut;
1122
1123 $name = substr( $oldimage, 15 );
1124 $archive = wfImageArchiveDir( $name );
1125 if ( ! unlink( "{$archive}/{$oldimage}" ) ) {
1126 $wgOut->fileDeleteError( "{$archive}/{$oldimage}" );
1127 }
1128 }
1129
1130 function doDeleteArticle( $title )
1131 {
1132 global $wgUser, $wgOut, $wgLang, $wpReason, $wgTitle, $wgDeferredUpdateList;
1133
1134 $fname = "Article::doDeleteArticle";
1135 $ns = $title->getNamespace();
1136 $t = wfStrencode( $title->getDBkey() );
1137 $id = $title->getArticleID();
1138
1139 if ( "" == $t ) {
1140 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
1141 return;
1142 }
1143
1144 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1145 array_push( $wgDeferredUpdateList, $u );
1146
1147 # Move article and history to the "archive" table
1148 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1149 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1150 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
1151 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
1152 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1153 wfQuery( $sql, $fname );
1154
1155 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
1156 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
1157 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
1158 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
1159 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1160 wfQuery( $sql, $fname );
1161
1162 # Now that it's safely backed up, delete it
1163
1164 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1165 "cur_title='{$t}'";
1166 wfQuery( $sql, $fname );
1167
1168 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1169 "old_title='{$t}'";
1170 wfQuery( $sql, $fname );
1171
1172 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1173 "rc_title='{$t}'";
1174 wfQuery( $sql, $fname );
1175
1176 # Finally, clean up the link tables
1177
1178 if ( 0 != $id ) {
1179 $t = wfStrencode( $title->getPrefixedDBkey() );
1180 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
1181 $res = wfQuery( $sql, $fname );
1182
1183 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
1184 $now = wfTimestampNow();
1185 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
1186 $first = true;
1187
1188 while ( $s = wfFetchObject( $res ) ) {
1189 $nt = Title::newFromDBkey( $s->l_from );
1190 $lid = $nt->getArticleID();
1191
1192 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
1193 $first = false;
1194 $sql .= "({$lid},'{$t}')";
1195 $sql2 .= "{$lid}";
1196 }
1197 $sql2 .= ")";
1198 if ( ! $first ) {
1199 wfQuery( $sql, $fname );
1200 wfQuery( $sql2, $fname );
1201 }
1202 wfFreeResult( $res );
1203
1204 $sql = "DELETE FROM links WHERE l_to={$id}";
1205 wfQuery( $sql, $fname );
1206
1207 $sql = "DELETE FROM links WHERE l_from='{$t}'";
1208 wfQuery( $sql, $fname );
1209
1210 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
1211 wfQuery( $sql, $fname );
1212
1213 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1214 wfQuery( $sql, $fname );
1215 }
1216
1217 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
1218 $art = $title->getPrefixedText();
1219 $wpReason = wfCleanQueryVar( $wpReason );
1220 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
1221
1222 # Clear the cached article id so the interface doesn't act like we exist
1223 $wgTitle->resetArticleID( 0 );
1224 $wgTitle->mArticleID = 0;
1225 }
1226
1227 function revert()
1228 {
1229 global $wgOut;
1230 global $oldimage;
1231
1232 if ( strlen( $oldimage ) < 16 ) {
1233 $wgOut->unexpectedValueError( "oldimage", $oldimage );
1234 return;
1235 }
1236 if ( wfReadOnly() ) {
1237 $wgOut->readOnlyPage();
1238 return;
1239 }
1240 $name = substr( $oldimage, 15 );
1241
1242 $dest = wfImageDir( $name );
1243 $archive = wfImageArchiveDir( $name );
1244 $curfile = "{$dest}/{$name}";
1245
1246 if ( ! is_file( $curfile ) ) {
1247 $wgOut->fileNotFoundError( $curfile );
1248 return;
1249 }
1250 $oldver = wfTimestampNow() . "!{$name}";
1251 $size = wfGetSQL( "oldimage", "oi_size", "oi_archive_name='" .
1252 wfStrencode( $oldimage ) . "'" );
1253
1254 if ( ! rename( $curfile, "${archive}/{$oldver}" ) ) {
1255 $wgOut->fileRenameError( $curfile, "${archive}/{$oldver}" );
1256 return;
1257 }
1258 if ( ! copy( "{$archive}/{$oldimage}", $curfile ) ) {
1259 $wgOut->fileCopyError( "${archive}/{$oldimage}", $curfile );
1260 }
1261 wfRecordUpload( $name, $oldver, $size, wfMsg( "reverted" ) );
1262
1263 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1264 $wgOut->setRobotpolicy( "noindex,nofollow" );
1265 $wgOut->addHTML( wfMsg( "imagereverted" ) );
1266 $wgOut->returnToMain( false );
1267 }
1268
1269 function rollback()
1270 {
1271 global $wgUser, $wgTitle, $wgLang, $wgOut;
1272
1273 if ( ! $wgUser->isSysop() ) {
1274 $wgOut->sysopRequired();
1275 return;
1276 }
1277
1278 # Replace all this user's current edits with the next one down
1279 $tt = wfStrencode( $wgTitle->getDBKey() );
1280 $n = $wgTitle->getNamespace();
1281
1282 # Get the last editor
1283 $sql = "SELECT cur_id,cur_user,cur_user_text FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1284 $res = wfQuery( $sql );
1285 if( ($x = wfNumRows( $res )) != 1 ) {
1286 # Something wrong
1287 $wgOut->addHTML( wfMsg( "notanarticle" ) );
1288 return;
1289 }
1290 $s = wfFetchObject( $res );
1291 $ut = wfStrencode( $s->cur_user_text );
1292 $uid = $s->cur_user;
1293 $pid = $s->cur_id;
1294
1295 # Get the last edit not by this guy
1296 $sql = "SELECT old_text,old_user,old_user_text
1297 FROM old USE INDEX (name_title_timestamp)
1298 WHERE old_namespace={$n} AND old_title='{$tt}'
1299 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1300 ORDER BY inverse_timestamp LIMIT 1";
1301 $res = wfQuery( $sql );
1302 if( wfNumRows( $res ) != 1 ) {
1303 # Something wrong
1304 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1305 return;
1306 }
1307 $s = wfFetchObject( $res );
1308
1309 # Save it!
1310 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
1311 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1312 $wgOut->setRobotpolicy( "noindex,nofollow" );
1313 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1314 $this->updateArticle( $s->old_text, $newcomment, 1, $wgTitle->userIsWatching() );
1315
1316 $wgOut->returnToMain( false );
1317 }
1318
1319
1320 # Do standard deferred updates after page view
1321
1322 /* private */ function viewUpdates()
1323 {
1324 global $wgDeferredUpdateList, $wgTitle;
1325
1326 if ( 0 != $this->getID() ) {
1327 $u = new ViewCountUpdate( $this->getID() );
1328 array_push( $wgDeferredUpdateList, $u );
1329 $u = new SiteStatsUpdate( 1, 0, 0 );
1330 array_push( $wgDeferredUpdateList, $u );
1331
1332 $u = new UserTalkUpdate( 0, $wgTitle->getNamespace(),
1333 $wgTitle->getDBkey() );
1334 array_push( $wgDeferredUpdateList, $u );
1335 }
1336 }
1337
1338 # Do standard deferred updates after page edit.
1339 # Every 1000th edit, prune the recent changes table.
1340
1341 /* private */ function editUpdates( $text )
1342 {
1343 global $wgDeferredUpdateList, $wgTitle;
1344
1345 wfSeedRandom();
1346 if ( 0 == mt_rand( 0, 999 ) ) {
1347 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1348 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1349 wfQuery( $sql );
1350 }
1351 $id = $this->getID();
1352 $title = $wgTitle->getPrefixedDBkey();
1353 $adj = $this->mCountAdjustment;
1354
1355 if ( 0 != $id ) {
1356 $u = new LinksUpdate( $id, $title );
1357 array_push( $wgDeferredUpdateList, $u );
1358 $u = new SiteStatsUpdate( 0, 1, $adj );
1359 array_push( $wgDeferredUpdateList, $u );
1360 $u = new SearchUpdate( $id, $title, $text );
1361 array_push( $wgDeferredUpdateList, $u );
1362
1363 $u = new UserTalkUpdate( 1, $wgTitle->getNamespace(),
1364 $wgTitle->getDBkey() );
1365 array_push( $wgDeferredUpdateList, $u );
1366 }
1367 }
1368
1369 /* private */ function setOldSubtitle()
1370 {
1371 global $wgLang, $wgOut;
1372
1373 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1374 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1375 $wgOut->setSubtitle( "({$r})" );
1376 }
1377
1378 function blockedIPpage()
1379 {
1380 global $wgOut, $wgUser, $wgLang;
1381
1382 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
1383 $wgOut->setRobotpolicy( "noindex,nofollow" );
1384 $wgOut->setArticleFlag( false );
1385
1386 $id = $wgUser->blockedBy();
1387 $reason = $wgUser->blockedFor();
1388
1389 $name = User::whoIs( $id );
1390 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
1391 ":{$name}|{$name}]]";
1392
1393 $text = str_replace( "$1", $link, wfMsg( "blockedtext" ) );
1394 $text = str_replace( "$2", $reason, $text );
1395 $wgOut->addWikiText( $text );
1396 $wgOut->returnToMain( false );
1397 }
1398
1399 # This function is called right before saving the wikitext,
1400 # so we can do things like signatures and links-in-context.
1401
1402 function preSaveTransform( $text )
1403 {
1404 $s = "";
1405 while ( "" != $text ) {
1406 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1407 $s .= $this->pstPass2( $p[0] );
1408
1409 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1410 else {
1411 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1412 $s .= "<nowiki>{$q[0]}</nowiki>";
1413 $text = $q[1];
1414 }
1415 }
1416 return rtrim( $s );
1417 }
1418
1419 /* private */ function pstPass2( $text )
1420 {
1421 global $wgUser, $wgLang, $wgTitle, $wgLocaltimezone;
1422
1423 # Signatures
1424 #
1425 $n = $wgUser->getName();
1426 $k = $wgUser->getOption( "nickname" );
1427 if ( "" == $k ) { $k = $n; }
1428 if(isset($wgLocaltimezone)) {
1429 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1430 }
1431 $d = $wgLang->timeanddate( wfTimestampNow(), false ) .
1432 " (" . date( "T" ) . ")";
1433 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1434
1435 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1436 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1437 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1438 Namespace::getUser() ) . ":$n|$k]]", $text );
1439
1440 # Context links: [[|name]] and [[name (context)|]]
1441 #
1442 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1443 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1444 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1445
1446 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1447 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1448 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1449 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1450 # [[ns:page (cont)|]]
1451 $context = "";
1452 $t = $wgTitle->getText();
1453 if ( preg_match( $conpat, $t, $m ) ) {
1454 $context = $m[2];
1455 }
1456 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1457 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1458 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1459
1460 if ( "" == $context ) {
1461 $text = preg_replace( $p2, "[[\\1]]", $text );
1462 } else {
1463 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1464 }
1465 # Replace local image links with new [[image:]] style
1466
1467 $text = preg_replace(
1468 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/upload\/" .
1469 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1470 "\\1[[image:\\3.\\4]]", $text );
1471 $text = preg_replace(
1472 "/(^|[^[])http:\/\/(www.|)wikipedia.com\/images\/uploads\/" .
1473 "([a-zA-Z0-9_:.~\%\-]+)\.(png|PNG|jpg|JPG|jpeg|JPEG|gif|GIF)/",
1474 "\\1[[image:\\3.\\4]]", $text );
1475
1476 return $text;
1477 }
1478
1479
1480 /* Caching functions */
1481
1482 function tryFileCache() {
1483 if($this->isFileCacheable()) {
1484 if($this->isFileCacheGood()) {
1485 wfDebug( " tryFileCache() - about to load\n" );
1486 $this->loadFromFileCache();
1487 exit;
1488 } else {
1489 wfDebug( " tryFileCache() - starting buffer\n" );
1490 ob_start( array(&$this, 'saveToFileCache' ) );
1491 }
1492 } else {
1493 wfDebug( " tryFileCache() - not cacheable\n" );
1494 }
1495 }
1496
1497 function isFileCacheable() {
1498 global $wgUser, $wgTitle, $wgUseFileCache, $wgShowIPinHeader;
1499 global $action, $oldid, $diff, $redirect, $printable;
1500 return $wgUseFileCache
1501 and (!$wgShowIPinHeader)
1502 and ($wgUser->getId() == 0)
1503 and (!$wgUser->getNewtalk())
1504 and ($wgTitle->getNamespace != Namespace::getSpecial())
1505 and ($action == "view")
1506 and (!isset($oldid))
1507 and (!isset($diff))
1508 and (!isset($redirect))
1509 and (!isset($printable))
1510 and (!$this->mRedirectedFrom);
1511
1512 }
1513
1514 function fileCacheName() {
1515 global $wgTitle, $wgFileCacheDirectory, $wgLang;
1516 if( !$this->mFileCache ) {
1517 $hash = md5( $key = $wgTitle->getDbkey() );
1518 if( $wgTitle->getNamespace() )
1519 $key = $wgLang->getNsText( $wgTitle->getNamespace() ) . ":" . $key;
1520 $key = str_replace( ".", "%2E", urlencode( $key ) );
1521 $hash1 = substr( $hash, 0, 1 );
1522 $hash2 = substr( $hash, 0, 2 );
1523 $this->mFileCache = "{$wgFileCacheDirectory}/{$hash1}/{$hash2}/{$key}.html";
1524 wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
1525 }
1526 return $this->mFileCache;
1527 }
1528
1529 function isFileCacheGood() {
1530 global $wgUser, $wgCacheEpoch;
1531 if(!file_exists( $fn = $this->fileCacheName() ) ) return false;
1532 $cachetime = wfUnix2Timestamp( filemtime( $fn ) );
1533 $good = ( $this->mTouched <= $cachetime ) &&
1534 ($wgCacheEpoch <= $cachetime );
1535 wfDebug(" isFileCacheGood() - cachetime $cachetime, touched {$this->mTouched} epoch {$wgCacheEpoch}, good $good\n");
1536 return $good;
1537 }
1538
1539 function loadFromFileCache() {
1540 global $wgUseGzip;
1541 wfDebug(" loadFromFileCache()\n");
1542 $filename=$this->fileCacheName();
1543 $filenamegz = "{$filename}.gz";
1544 if( $wgUseGzip
1545 && wfClientAcceptsGzip()
1546 && file_exists( $filenamegz)
1547 && ( filemtime( $filenamegz ) >= filemtime( $filename ) ) ) {
1548 wfDebug(" sending gzip\n");
1549 header( "Content-Encoding: gzip" );
1550 header( "Vary: Accept-Encoding" );
1551 $filename = $filenamegz;
1552 }
1553 readfile( $filename );
1554 }
1555
1556 function saveToFileCache( $text ) {
1557 global $wgUseGzip, $wgCompressByDefault;
1558
1559 wfDebug(" saveToFileCache()\n");
1560 $filename=$this->fileCacheName();
1561 $mydir2=substr($filename,0,strrpos($filename,"/")); # subdirectory level 2
1562 $mydir1=substr($mydir2,0,strrpos($mydir2,"/")); # subdirectory level 1
1563 if(!file_exists($mydir1)) { mkdir($mydir1,0777); } # create if necessary
1564 if(!file_exists($mydir2)) { mkdir($mydir2,0777); }
1565 $f = fopen( $filename, "w" );
1566 if($f) {
1567 $now = wfTimestampNow();
1568 fwrite( $f, str_replace( "</html>",
1569 "<!-- Cached $now -->\n</html>",
1570 $text ) );
1571 fclose( $f );
1572 if( $wgUseGzip and $wgCompressByDefault ) {
1573 $start = microtime();
1574 wfDebug(" saving gzip\n");
1575 $gzout = gzencode( str_replace( "</html>",
1576 "<!-- Cached/compressed $now -->\n</html>",
1577 $text ) );
1578 if( $gzout === false ) {
1579 wfDebug(" failed to gzip compress, sending plaintext\n");
1580 return $text;
1581 }
1582 if( $f = fopen( "{$filename}.gz", "w" ) ) {
1583 fwrite( $f, $gzout );
1584 fclose( $f );
1585 $end = microtime();
1586
1587 list($usec1, $sec1) = explode(" ",$start);
1588 list($usec2, $sec2) = explode(" ",$end);
1589 $interval = ((float)$usec2 + (float)$sec2) -
1590 ((float)$usec1 + (float)$sec1);
1591 wfDebug(" saved gzip in $interval\n");
1592 } else {
1593 wfDebug(" failed to write gzip, still sending\n" );
1594 }
1595 header( "Content-Encoding: gzip" );
1596 header( "Vary: Accept-Encoding" );
1597 return $gzout;
1598 }
1599 }
1600 return $text;
1601 }
1602
1603 }
1604
1605 ?>